<template>
    <view class="container">
        <!-- 顶部导航栏 -->
        <view class="header">
            <text class="title">我的订单</text>
        </view>
        
        <!-- Tab导航 -->
        <view class="tab-nav">
            <view 
                v-for="(tab, index) in tabs" 
                :key="index"
                class="tab-item"
                :class="{ active: currentTab === index }"
                @click="switchTab(index)"
            >
                {{ tab }}
                <view v-if="currentTab === index" class="tab-indicator"></view>
            </view>
        </view>

        <!-- 订单列表 -->
        <scroll-view scroll-y class="order-list" :style="{height: scrollViewHeight + 'px'}">
            <!-- 空状态 -->
            <view v-if="filteredOrders.length === 0" class="empty-state">
                <image src="/static/empty-order.png" class="empty-image"></image>
                <text class="empty-text">暂无相关订单</text>
                <text class="empty-tip">去逛逛吧~</text>
            </view>
            
            <!-- 订单项 -->
            <view v-for="order in filteredOrders" :key="order.id" class="order-item">
                <!-- 订单头部 -->
                <view class="order-header">
                    <view class="store-info">
                        <image src="/static/store-icon.png" class="store-icon"></image>
                        <text class="store-name">{{ order.storeName }}</text>
                        <image src="/static/arrow-right.png" class="arrow-icon"></image>
                    </view>
                    <!-- 修改：根据状态添加类名 -->
                    <text 
                        class="order-status" 
                        :class="{ 
                            'status-waiting-delivery': order.status === '待配送',
                            'status-in-delivery': order.status === '配送中',
                            'status-completed': order.status === '已完成',
                            'status-cancelled': order.status === '已取消'
                        }"
                    >
                        {{ order.status }}
                    </text>
                </view>
                
               <!-- 修改后 -->
<view class="order-info-row">
    <text class="info-label">订单编号：</text>
    <text class="info-value">{{ order.orderNumber || '暂无编号' }}</text>
</view>

                <!-- 订单内容 -->
                <view class="order-content">
                    <!-- 商品图片 -->
                    <view class="product-images">
                        <image 
                            v-for="(item, index) in order.items.slice(0, 3)" 
                            :key="index"
                            :src="`/static/${item.imgUrl}`"
                            mode="aspectFill"
                            class="product-image"
                            :style="{zIndex: 10-index}"
                        ></image>
                        <view v-if="order.items.length > 3" class="more-products">
                            +{{ order.items.length - 3 }}
                        </view>
                    </view>
                    
                    <!-- 订单信息 -->
                    <view class="order-info">
                        <view class="price-quantity">
                            <text class="price">¥{{ formatPrice(order.totalAmount) }}</text>
                            <text class="quantity">共{{ getTotalQuantity(order) }}件</text>
                        </view>
                        <view class="order-time">下单时间：{{ formatTime(order.createTime) }}</view>
                    </view>
                </view>

                <!-- 新增：商品名称列表 -->
                <view class="product-names">
                    <text class="product-names-label">商品名称:</text>
                    <view v-for="(item, index) in order.items" :key="index" class="product-name-item">
                        <text>{{ item.name }}</text>
                        <text class="product-quantity">x{{ item.quantity }}</text>
                    </view>
                </view>

                <!-- 订单操作按钮 -->
                <view class="order-footer">
                    <button 
                        v-if="order.status === '配送中'"
                        class="action-button confirm"
                        @click.stop="confirmReceipt(order)"
                    >
                        确认收货
                    </button>
                    <button 
                        v-if="['已完成', '已取消'].includes(order.status)"
                        class="action-button delete"
                        @click.stop="deleteOrder(order)"
                    >
                        删除订单
                    </button>
                    <button 
                        v-if="order.status === '已完成'"
                        class="action-button"
                        @click.stop="buyAgain(order)"
                    >
                        再次购买
                    </button>
                </view>
            </view>
        </scroll-view>
    </view>
</template>

<script>
export default {
    data() {
        return {
            tabs: ['全部', '待配送', '已完成', '已取消'],
            currentTab: 0,
            orders: [],
            scrollViewHeight: 0
        }
    },
    computed: {
        filteredOrders() {
            switch(this.currentTab) {
                case 0: return this.orders;
                case 1: return this.orders.filter(o => o.status === '待配送');
                case 2: return this.orders.filter(o => o.status === '已完成');
                case 3: return this.orders.filter(o => o.status === '已取消');
                default: return this.orders;
            }
        }
    },
    onLoad() {
        this.calculateScrollViewHeight();
    },
    onShow() {
        this.loadOrders();
    },
    methods: {
        calculateScrollViewHeight() {
            const systemInfo = uni.getSystemInfoSync();
            this.scrollViewHeight = systemInfo.windowHeight - 180; // 减去头部和tab栏高度
        },
        switchTab(index) {
            this.currentTab = index;
        },
        getTotalQuantity(order) {
            return order.items.reduce((total, item) => total + item.quantity, 0);
        },
        formatPrice(price) {
            return parseFloat(price).toFixed(2);
        },
        formatTime(timestamp) {
            if (!timestamp) return '';
            const date = new Date(timestamp);
            return `${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}`;
        },
        loadOrders() {
            uni.showLoading({ title: '加载中...', mask: true });
            
            const currentPhone = uni.getStorageSync('currentPhone');
            uni.request({
                url: 'https://67f85eae7719dfcd4b47e8f1.hz-iframe-svc.simplelab.cn/users',
                method: 'GET',
                success: (res) => {
                    uni.hideLoading();
                    if (res.statusCode === 200) {
                        const currentUser = res.data.find(user => user.phone === currentPhone);
                        if (currentUser && currentUser.order) {
                            this.orders = currentUser.order.map(order => ({
                                ...order,
                                orderNumber: order.orderNumber || this.generateOrderNumber(), // 确保有订单编号
                                totalAmount: parseFloat(order.totalAmount) || 0,
                                createTime: order.createTime || Date.now()
                            })).sort((a, b) => b.createTime - a.createTime);
                        }
                    }
                },
                fail: () => {
                    uni.hideLoading();
                    uni.showToast({ title: '加载失败', icon: 'none' });
                }
            });
        },
        // 新增方法：生成订单编号
        generateOrderNumber() {
            const date = new Date();
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
            return `${year}${month}${day}${random}`;
        },
        confirmReceipt(order) {
            uni.showModal({
                title: '确认收货',
                content: '请确认已收到商品，确认后订单将完成',
                success: (res) => {
                    if (res.confirm) {
                        this.updateOrderStatus(order.id, '已完成');
                    }
                }
            });
        },
        deleteOrder(order) {
            uni.showModal({
                title: '删除订单',
                content: '确定要删除此订单吗？删除后不可恢复',
                success: (res) => {
                    if (res.confirm) {
                        this.orders = this.orders.filter(o => o.id !== order.id);
                        this.syncOrdersToServer();
                        uni.showToast({ title: '删除成功', icon: 'success' });
                    }
                }
            });
        },
        buyAgain(order) {
            // 模拟再次购买逻辑
            uni.showLoading({ title: '加入购物车中...' });
            setTimeout(() => {
                uni.hideLoading();
                uni.showToast({ title: '商品已加入购物车', icon: 'success' });
                uni.switchTab({ url: '/pages/cart/cart' });
            }, 1000);
        },
        updateOrderStatus(orderId, newStatus) {
            this.orders = this.orders.map(order => 
                order.id === orderId ? { ...order, status: newStatus } : order
            );
            this.syncOrdersToServer();
            uni.showToast({ title: '操作成功', icon: 'success' });
        },
        syncOrdersToServer() {
            const currentPhone = uni.getStorageSync('currentPhone');
            uni.request({
                url: 'https://67f85eae7719dfcd4b47e8f1.hz-iframe-svc.simplelab.cn/users',
                method: 'GET',
                success: (res) => {
                    if (res.statusCode === 200) {
                        const currentUser = res.data.find(user => user.phone === currentPhone);
                        if (currentUser) {
                            uni.request({
                                url: `https://67f85eae7719dfcd4b47e8f1.hz-iframe-svc.simplelab.cn/users/${currentUser.id}`,
                                method: 'PUT',
                                data: { ...currentUser, order: this.orders }
                            });
                        }
                    }
                }
            });
        }
    }
}
</script>

<style scoped>

/* 全局样式 */
.container {
    min-height: 100vh;
    background-color: #f7f7f7;
    font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
}

/* 头部样式 */
.header {
    height: 88rpx;
    background: linear-gradient(135deg, #0099FF, #5F9FFF);
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    font-size: 36rpx;
    font-weight: 500;
    position: relative;
}

.header .title {
    letter-spacing: 2rpx;
}

/* Tab导航样式 */
.tab-nav {
    display: flex;
    background-color: #fff;
    position: relative;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
    padding: 0 20rpx;
}

.tab-item {
    flex: 1;
    text-align: center;
    padding: 24rpx 0;
    font-size: 30rpx;
    color: #666;
    position: relative;
    transition: all 0.3s;
}

.tab-item.active {
    color: #0099FF;
    font-weight: 500;
}

.tab-indicator {
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    width: 60rpx;
    height: 6rpx;
    background-color: #0099FF;
    border-radius: 3rpx;
}

/* 订单列表样式 */
.order-list {
    padding: 20rpx;
    box-sizing: border-box;
}

.empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 100rpx 0;
}

.empty-image {
    width: 300rpx;
    height: 300rpx;
    opacity: 0.6;
    margin-bottom: 30rpx;
}

.empty-text {
    font-size: 32rpx;
    color: #999;
    margin-bottom: 10rpx;
}

.empty-tip {
    font-size: 28rpx;
    color: #ccc;
}

.order-item {
    background-color: #fff;
    border-radius: 16rpx;
    margin-bottom: 20rpx;
    overflow: hidden;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.03);
    transition: transform 0.2s;
}

.order-item:active {
    transform: scale(0.99);
}

.order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 24rpx;
    border-bottom: 1rpx solid #f5f5f5;
}

.store-info {
    display: flex;
    align-items: center;
}

.store-icon {
    width: 36rpx;
    height: 36rpx;
    margin-right: 12rpx;
}

.store-name {
    font-size: 30rpx;
    color: #333;
    font-weight: 500;
    max-width: 300rpx;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.arrow-icon {
    width: 24rpx;
    height: 24rpx;
    margin-left: 10rpx;
    opacity: 0.5;
}

.order-status {
    font-size: 26rpx;
    padding: 6rpx 16rpx;
    border-radius: 30rpx;
}

/* 新增：订单状态样式 */
.status-waiting-delivery {
    color: #FF9500;
    background-color: #FFF4E5;
}

.status-in-delivery {
    color: #0099FF;
    background-color: #E6F7FF;
}

.status-completed {
    color: #34C759;
    background-color: #E6F7EC;
}

.status-cancelled {
    color: #FF3B30;
    background-color: #FFEBE9;
}

.order-person-info {
    display: flex;
    align-items: center;
    padding: 16rpx 24rpx;
    border-bottom: 1rpx solid #f5f5f5;
}

.order-person-label {
    font-size: 26rpx;
    color: #999;
    margin-right: 10rpx;
}

.order-person-name {
    font-size: 26rpx;
    color: #333;
}

.order-content {
    display: flex;
    padding: 24rpx;
    position: relative;
}

.product-images {
    display: flex;
    margin-right: 20rpx;
    position: relative;
}

.product-image {
    width: 140rpx;
    height: 140rpx;
    border-radius: 8rpx;
    border: 1rpx solid #f5f5f5;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.product-image:not(:first-child) {
    margin-left: -30rpx;
}

.more-products {
    position: absolute;
    right: 10rpx;
    bottom: 10rpx;
    background-color: rgba(0, 0, 0, 0.5);
    color: #fff;
    font-size: 22rpx;
    padding: 4rpx 12rpx;
    border-radius: 30rpx;
}

.order-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: flex-end;
}

.price-quantity {
    text-align: right;
}

.price {
    font-size: 36rpx;
    color: #FF4D4F;
    font-weight: 600;
    line-height: 1.4;
}

.quantity {
    font-size: 26rpx;
    color: #999;
}

.order-time {
    font-size: 24rpx;
    color: #ccc;
}

.product-names {
    padding: 16rpx 24rpx;
    border-top: 1rpx solid #f5f5f5;
}

.product-names-label {
    font-size: 26rpx;
    color: #999;
    display: block;
    margin-bottom: 10rpx;
}

.product-name-item {
    display: flex;
    align-items: center;
    font-size: 26rpx;
    color: #333;
    margin-bottom: 8rpx;
}

.product-quantity {
    color: #999;
    margin-left: 8rpx;
}

.order-footer {
    display: flex;
    justify-content: flex-end;
    padding: 20rpx 24rpx;
    border-top: 1rpx solid #f5f5f5;
}

.action-button {
    font-size: 26rpx;
    padding: 8rpx 24rpx;
    border-radius: 30rpx;
    background-color: #fff;
    border: 1rpx solid #ddd;
    color: #666;
    margin-left: 20rpx;
    transition: all 0.2s;
}

.action-button:active {
    opacity: 0.8;
}

.action-button.confirm {
    background-color: #0099FF;
    color: #fff;
    border: none;
}

.action-button.delete {
    color: #FF4D4F;
    border-color: #FF4D4F;
}
</style>